﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common;
using Common.Request;
using System.Collections;
//using Utils_kuaidi100;
using System.Web.Script.Serialization;
using System.Net;
using System.Text;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using Common.Request.Electronic.Image;

/// <summary>
/// program 的摘要说明
/// </summary>
public class Kuaidi100
{
    public Kuaidi100()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    //授权KEY
    //EQVMDedr3816

    //customer
    //4D8AA66E9B8199032E7E6C2932510DCE

    //secret
    //4f117d49b5f7429480fce3d34611fa8c

    //userid
    //579f237d07994c8c83d8e7abbb822784

    //智能判断
    //EQVMDedr3816

    private static KuaiDi100Config config = new KuaiDi100Config()
    {
        key = "EQVMDedr3816",
        customer = "4D8AA66E9B8199032E7E6C2932510DCE",
        secret = "4f117d49b5f7429480fce3d34611fa8c",
        userid = "579f237d07994c8c83d8e7abbb822784",
    };

    /// <summary>
    /// 查询物流轨迹,ems查询的快递公司的编码一律用小写字母,快递单号,手机号
    /// </summary>
    /// 
    //└ com	String	必须	ems	查询的快递公司的编码，一律用小写字母
    //└ num	String	必须	EM263999513JP	查询的快递单号， 单号的最大长度是32个字符
    //└ phone	String	可选	13868688888	收件人或寄件人的手机号或固话（顺丰单号必填，也可以填写后四位，如果是固话，请不要上传分机号）
    //└ from	String	可选	广东省深圳市南山区	出发地城市，省-市-区，填了有助于提升签收状态的判断的准确率，请尽量提供
    //└ to	String	可选	北京市朝阳区	目的地城市，省-市-区，填了有助于提升签收状态的判断的准确率，请尽量提供
    //└ resultv2	String	可选	1	添加此字段表示开通行政区域解析功能。0：关闭（默认），1：开通行政区域解析功能，2：开通行政解析功能并且返回出发、目的及当前城市信息
    //└ show	String	可选	0	返回数据格式。0：json（默认），1：xml，2：html，3：text
    //└ order	String	可选	desc	返回结果排序方式。desc：降序（默认），asc：升序

    //Kuaidi100.testQueryTrack("jd", "JDVD00937418017", "13973110915");string _com,string _num, string _phone
    //public static void getQueryTrack()
    //{
    //    //var queryTrackParam = new QueryTrackParam()
    //    //{
    //    //    com = "jd",
    //    //    num = "JDVD00937418017",
    //    //    from=" ",
    //    //    phone = "13973110915",
    //    //    to=" ",
    //    //    resultv2 = "0",
    //    //    show = "2",
    //    //    order= "desc",
    //    //};

    //    //query(new QueryTrackReq()
    //    //{
    //    //    customer = config.customer,
    //    //    sign = SignUtils.GetMD5(queryTrackParam.ToString() + config.key + config.customer),
    //    //    param = queryTrackParam
    //    //});
    //    //ApiInfoConstant.QUERY_URL,request

    //    //http://poll.kuaidi100.com/poll/query.do?customer=C75C1F6062EFA5A7936F44F425390168&sign=E4D4F121403436AE1FEBC1E6020CCEE5&param={"com":"jd","num":"JDVD00937418017","from":"","phone":"","to":"","resultv2":"0","show":"2","order":"desc"}

    //}

    /// <summary>
    /// 物流查询
    /// </summary>
    public static string query(string _com, string _num, string _phone)
    {
        var queryTrackParam = new QueryTrackParam()
        {
            com = _com,
            num = _num,
            from = " ",
            phone = _phone,
            to = " ",
            resultv2 = "0",
            show = "0",
            order = "desc",
        };

        var _data = new QueryTrackReq()
        {
            customer = config.customer,
            sign = GetMD5(queryTrackParam.ToString() + config.key + config.customer),
            param = queryTrackParam
        };

        var request = ObjectToMap(_data);
        if (request == null)
        {
            return null;
        }
        var result = Post(ApiInfoConstant.QUERY_URL, request);
        return result;
    }

    /// <summary>
    /// 电子面单图片接口
    /// </summary>
    /// https://poll.kuaidi100.com/printapi/printtask.do?method=getPrintImg&key=EQVMDedr3816&sign=FD2DC27B394F698443B32A182A6FDE1C&t=1602577801000&param={"type":"10","partnerId":"6505007952","partnerKey":"ushHK8Y69NWgJGPnDq5mEyeUB7CwTc","net":"","kuaidicom":"yunda","recManName":"陈家财","recManMobile":"18288957346","recManPrintAddr":"云南省昆明市盘龙区电子商务创业园","sendManName":"苏一伦","sendManMobile":"18584892365","sendManPrintAddr":"云南省昆明市呈贡东盟森林","tempid":"9fe54ed8e1fe4c639a2020bab8a3dac8","cargo":"化妆品","count":"1","weight":"1","payType":"SHIPPER","expType":"标准快递","remark":"订单号6778999"}
    /// 快递公司编码，寄件人姓名，寄件人电话，寄件人地址，收件人姓名，收件人号码，收件人地址，物品名称，数量，重量KG，备注
    public static string testPrintImg(string _kuaidicom, string _sendManName, string _sendManMobile, string _sendManPrintAddr, string _recManName, string _recManMobile, string _recManPrintAddr, string _cargo, string _count, string _weight, string _remark)
    {
        var printImgParam = new PrintImgParam()
        {
            //partnerId = "6505007952",
            //partnerKey = "ushHK8Y69NWgJGPnDq5mEyeUB7CwTc",
            partnerId = "6f5cf230e8f5",
            partnerKey = "594c7162a43540aca759ef6005a5c47a",
            //kuaidicom = "zhaijisong",
            //sendManName = "张三",
            //sendManMobile = "15999998256",
            //sendManPrintAddr = "广东省深圳市南山区科技南十二路",
            //recManName = "李四",
            //recManMobile = "15999998256",
            //recManPrintAddr = "北京市海淀区1路",
            //type = "10",
            //tempid = "180c7c8f646742ca871a92c976392b05",
            //count = "1",
            ////weight = "1.5",
            //width = "76",
            //height = "130",
            kuaidicom = _kuaidicom,
            sendManName = _sendManName,
            sendManMobile = _sendManMobile,
            sendManPrintAddr = _sendManPrintAddr,
            recManName = _recManName,
            recManMobile = _recManMobile,
            recManPrintAddr = _recManPrintAddr,
            //tempid = "9fe54ed8e1fe4c639a2020bab8a3dac8",
            tempid = "e849b148feeb4dd187adc70d0c30b9e3",
            //cargo = methods.FilterChar(_cargo),
            //count = _count,
            remark = _remark,
            width = "76",
            height = "130",
        };

        var timestamp = GetTimestamp();
        var _data = new PrintImgReq()
        {
            method = ApiInfoConstant.ELECTRONIC_ORDER_PIC_METHOD,
            key = config.key,
            t = timestamp,
            sign = GetMD5(printImgParam.ToString() + timestamp + config.key + config.secret).ToUpper(),
            param = printImgParam,
        };

        var request = ObjectToMap(_data);

        if (request == null)
        {
            return null;
        }
        var result = Post(ApiInfoConstant.ELECTRONIC_ORDER_PRINT_URL, request);
        return result;
    }

    public static Dictionary<string, string> ObjectToMap(object obj)
    {
        Dictionary<string, string> map = new Dictionary<string, string>();

        Type t = obj.GetType(); // 获取对象对应的类， 对应的类型

        PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 获取当前type公共属性

        foreach (PropertyInfo p in pi)
        {
            MethodInfo m = p.GetGetMethod();

            if (m != null && m.IsPublic)
            {
                // 进行判NULL处理
                if (m.Invoke(obj, new object[] { }) != null)
                {
                    map.Add(p.Name, m.Invoke(obj, new object[] { })
                                     .ToString()); // 向字典添加元素
                }
            }
        }
        return map;
    }

    /// <summary>
    /// 指定Post地址使用Get 方式获取全部字符串
    /// </summary>
    /// <param name="url">请求后台地址</param>
    /// <returns></returns>
    /// 
    private static string Post(string url, Dictionary<string, string> dic)
    {
        string result = "";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        #region 添加Post 参数
        StringBuilder builder = new StringBuilder();
        int i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                builder.Append("&");
            builder.AppendFormat("{0}={1}", item.Key, item.Value);
            i++;
        }
        byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
        req.ContentLength = data.Length;
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();
        }
        #endregion
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        Stream stream = resp.GetResponseStream();
        //获取响应内容
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
        return result;
    }

    public static string GetMD5(string data)
    {
        using (var md5 = MD5.Create())
        {
            var hsah = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
            return BitConverter.ToString(hsah).Replace("-", "");
        }
    }

    public static string GetTimestamp()
    {
        TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
        return ts.TotalMilliseconds.ToString();
    }
}